package com.ynet.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ynet.excetion.PlatformErrorCode;
import com.ynet.h2.db.Message;
import com.ynet.h2.db.ReqData;
import com.ynet.h2.db.UserInfo;
import com.ynet.utils.MD5;

public class UserManage {
	private final static Logger logger = LoggerFactory.getLogger(UserManage.class);

	/**
	 * 公网访问请求处理
	 */
	public static void wanAppid(HttpServletRequest request, HttpServletResponse response) {

		StringBuffer url = request.getRequestURL();
		String uri = request.getRequestURI();
		String path = request.getContextPath();
		String uripath = uri.replaceAll(path + "/", "");

		// 获取 外网请求 appid
		int uripathWan = uripath.indexOf(".wan", 0);
		String appid = uripath.substring(0, uripathWan);
		String lanUrl = uripath.replace((appid + ".wan"), "");
		String method = request.getMethod();

		/**
		 * 判断请求是否是json 或者 form
		 */
		String type = request.getContentType();

		if (null != type && !"".equals(type)) {
			String dataJson = null;
			Map<String, String> dataMap = new Message().getMessage();

			if (type.indexOf("form") != -1) {
				// form请求
				dataMap = getFormData(request);
				if (dataMap != null && !dataMap.isEmpty()) {
					ReqData.saveReqData(appid, "form", dataMap.toString(), url.toString(), method, lanUrl, "1");
				}
			} else {
				dataJson = getJsonData(request);
				if (dataJson != null && !dataJson.equals("") && !dataJson.equals("{}")) {
					ReqData.saveReqData(appid, "json", dataJson, url.toString(), method, lanUrl, "1");
				}
			}
		}

		for (int i = 0; i < 1000; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Map<String, String> dataMap = ReqData.findAppId(appid, "2");// 查询内网响应
																		// 类型1-外网请求、2-内网响应
			if (!dataMap.isEmpty()) {
				String json = dataMap.get("req_data");

				if(json != null && !json.equals("")){
					UserManage.reswan(response, appid);
					ReqData.delReqDataByAppIdAndType(appid, "2");
					break;
				}
			}
			
		}

	}

	/**
	 * 内网访问请求处理
	 */
	public static void lanAppid(HttpServletRequest request, HttpServletResponse response) {

		String uri = request.getRequestURI();
		String path = request.getContextPath();
		String uripath = uri.replaceAll(path + "/", "");

		// 获取 内网请求 appid
		int uripathLan = uripath.indexOf(".lan", 0);

		String appid = uripath.substring(0, uripathLan);

		Map<String, String> dataMap = ReqData.findAppId(appid, "1");// 查询1-外网请求
																	// 类型1-外网请求、2-内网响应
		ReqData.delReqDataByAppIdAndType(appid, "1");

//		dataMap.put("returnCode", "000000");
//		dataMap.put("returnMsg", "成功");
		
		resJson(dataMap, response);

	}

	/**
	 * 内网响应处理 保存
	 */
	public static void reswan(HttpServletRequest request, HttpServletResponse response) {

		StringBuffer url = request.getRequestURL();
		String uri = request.getRequestURI();
		String path = request.getContextPath();
		String uripath = uri.replaceAll(path + "/", "");
		int uripathWan = uripath.indexOf(".reswan", 0); // 获取 外网请求 appid
		String appid = uripath.substring(0, uripathWan);
		String lanUrl = uripath.replace((appid + ".reswan"), "");
		String method = request.getMethod();

		/**
		 * 判断请求是否是json 或者 form
		 */
		String type = request.getContentType();

		if (null != type && !"".equals(type)) {
			String dataJson = null;
			Map<String, String> dataMap = new Message().getMessage();

			if (type.indexOf("form") != -1) {
				// form请求
				dataMap = getFormData(request);
				if (dataMap != null && !dataMap.isEmpty()) {
					ReqData.saveReqData(appid, "form", dataMap.toString(), url.toString(), method, lanUrl, "2");
				}
			} else {
				dataJson = getJsonData(request);
				if (dataJson != null && !dataJson.equals("") && !dataJson.equals("{}")) {
					ReqData.saveReqData(appid, "json", dataJson, url.toString(), method, lanUrl, "2");
				}
			}
		}
	}

	/**
	 * 内网响应处理 查询
	 */
	public static void reswan(HttpServletResponse response, String appid) {

		Map<String, String> dataMap = ReqData.findAppId(appid, "2");// 查询2-内网响应
																	// 类型1-外网请求、2-内网响应
		ReqData.delReqDataByAppIdAndType(appid, "2");

		logger.debug("------------" + dataMap.toString());

		String json = dataMap.get("req_data");

		JSONObject responseJSONObject = JSONObject.parseObject(json);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(responseJSONObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}

	}

	/**
	 * 用户登陆接口
	 * 
	 * @param request
	 */
	public static boolean logon(HttpServletRequest request, HttpServletResponse response) {

		String json = getJsonData(request);
		JSONObject jsonObject = JSONObject.parseObject(json);

		String appid = jsonObject.getString("appid");
		String password = jsonObject.getString("password");
		password = MD5.getMD5ofStr(password);

		boolean logon = new UserInfo().logonByAppidAndPassword(appid, password);

		if (!logon) {
			try {
				Map<String, String> dataMap = new Message().getMessage(PlatformErrorCode.error2, "用户名或密码错误请重新输入");
				resJson(dataMap, response);

				throw new Exception("用户名或密码错误请重新输入");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{

			Map<String, String> dataMap = new Message().getMessage();
			resJson(dataMap, response);

		}

		return logon;

	}

	/**
	 * 用户注册接口
	 * 
	 * @param request
	 */
	public static void register(HttpServletRequest request, HttpServletResponse response) {

		logger.debug("----UserManage register method--------" );

		String json = getJsonData(request);
		JSONObject jsonObject = JSONObject.parseObject(json);

		String appid = jsonObject.getString("appid");
		String password = jsonObject.getString("password");
		String user_name = jsonObject.getString("user_name");
		String agreement = jsonObject.getString("agreement");
		if (agreement == null || "".equals(agreement.trim())) {
			agreement = "1";// 默认http
		}
		logger.debug("----UserManage register method--------" + appid + " password:" + password  + " user_name:" + user_name);
		// 注册用户检查是否重复
		Map<String, String> dataMap = new UserInfo().findByAppid(appid);
		logger.debug("----UserManage register method--------!dataMap.get(\"appid\") " + dataMap.get("appid"));
		if (dataMap.get("appid") != null) {

			try {
				dataMap = new Message().getMessage(PlatformErrorCode.error1, "用户已经注册请更换用户名！");
				resJson(dataMap, response);
				throw new Exception("用户已经注册请更换用户名！");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			logger.debug("----UserManage register method----save");

			dataMap = new UserInfo().saveUserInfo(appid, user_name, password, agreement);
			resJson(dataMap, response);
		}

	}

	/**
	 * 处理json请求数据
	 */
	public static String getJsonData(HttpServletRequest request) {

		BufferedReader streamReader;
		JSONObject jsonObject = null;
		try {
			streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
			StringBuilder responseStrBuilder = new StringBuilder();
			String inputStr;
			while ((inputStr = streamReader.readLine()) != null)
				responseStrBuilder.append(inputStr);
			logger.debug(responseStrBuilder.toString());

			jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug(jsonObject.toJSONString());

		return jsonObject.toJSONString();
	}

	/**
	 * 处理form请求
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> getFormData(HttpServletRequest request) {
		Map<String, String> parmMap = new Message().getMessage();
		// // 方式一：getParameterMap()，获得请求参数map
		// Map<String, String[]> map = request.getParameterMap();
		// // 参数名称
		// Set<String> key = map.keySet();
		// // 参数迭代器
		// Iterator<String> iterator = key.iterator();
		// while (iterator.hasNext()) {
		// String k = iterator.next();
		// parmMap.put(k, map.get(k)[0]);
		// }
		// System.out.println("parmMap=====" + parmMap.toString());

		// 方式二：getParameterNames()：获取所有参数名称
		Enumeration<String> a = request.getParameterNames();
		String parm = null;
		String val = "";
		while (a.hasMoreElements()) {
			// 参数名
			parm = a.nextElement();
			// 值
			val = request.getParameter(parm);
			parmMap.put(parm, val);
		}
		// System.out.println("parmMap=========="+parmMap);

		JSON jsonObject = (JSON) JSONObject.toJSON(parmMap);

		// System.out.println(jsonObject.toJSONString());

		return parmMap;
	}

	/**
	 * 响应json数据
	 * @param dataMap
	 * @param response
	 */
	public static void resJson(Map dataMap, HttpServletResponse response){
		JSONObject responseJSONObject = (JSONObject) JSONObject.toJSON(dataMap);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.append(responseJSONObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}

	}
	
}
